package com.bulletelc.apollopre.module.display.product.details;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.adapter.ViewPageAdapter;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.ProductDetailAll;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.deal.clearing.ClearingActivity;
import com.bulletelc.apollopre.module.display.product.details.comment.CommentFragment;
import com.bulletelc.apollopre.module.display.product.details.detail.ProductDetailFragment;
import com.bulletelc.apollopre.module.display.product.details.introduce.IntroduceFragment;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.ShowShareDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.tauth.Tencent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * date  : 2017/12/26
 * desc  : 产品详情界面
 */

public class ProductDetailsActivity extends MVPBaseActivity<ProductDetailsContract.View, ProductDetailsPresenter> implements
        ProductDetailsContract.View, View.OnClickListener {

    // views
    private ImageView ivBack;
    private TabLayout tlMain;
    private ViewPager vpMain;
    private LinearLayout llCart;
    private LinearLayout llCollect;
    private TextView tvCollect;
    private ImageView ivCollect;
    private TextView tvAddToCart;
    private TextView tvBuyNow;
    public static ShowShareDialog showShareDialog; // 自定义分享的dialog

    // data
    private String productId; // 商品ID
    private int productSkuId = 0; // 商品规格ID
    private ProductDetailAll productDetailAll; // 商品详情
    private int wash_state = -1; // 是否收藏，1是 0否
    private int num = 1; // 商品购买数量,默认1
    private int release; // 是否下架
    private int install; // 是否安装
    private boolean showDialog = true; // 是否弹窗
    private List<String> title; // Fragment的Title
    private List<Fragment> fragments;
    private IntroduceFragment introduceFragment;
    private ProductDetailFragment productDetailFragment;
    private CommentFragment commentFragment;
    private ViewPageAdapter pageAdapter;
    private Tencent mTencent; // QQ
    private Bitmap weChatBip; // 微信分享的图片bitmap

    @Override
    public int getLayoutRes() {
        return R.layout.product_detail_activity;
    }

    @Override
    public void assignViews() {
        ivBack = findViewById(R.id.iBtnBack);
        tlMain = findViewById(R.id.tlMain);
        vpMain = findViewById(R.id.vpMain);
        llCart = findView(R.id.llCart);
        llCollect = findView(R.id.llCollect);
        tvCollect = findViewById(R.id.tvCollect);
        ivCollect = findView(R.id.ivCollect);
        tvAddToCart = findViewById(R.id.tvAddToCart);
        tvBuyNow = findView(R.id.tvBuyNow);
    }

    @Override
    public void setListener() {
        ivBack.setOnClickListener(this);
        llCart.setOnClickListener(this);
        llCollect.setOnClickListener(this);
        tvAddToCart.setOnClickListener(this);
        tvBuyNow.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (null != intent) {
            productId = intent.getStringExtra(IntentCode.EXTRA_KEY_PRODUCT_ID);
        }
        fragments = new ArrayList<>();
        title = new ArrayList<>();
        introduceFragment = new IntroduceFragment();
        productDetailFragment = new ProductDetailFragment();
        commentFragment = new CommentFragment();
        fragments.add(introduceFragment);
        fragments.add(productDetailFragment);
        fragments.add(commentFragment);
        title.add("商品");
        title.add("详情");
        title.add("评论");

        pageAdapter = new ViewPageAdapter(getSupportFragmentManager(), fragments, title);
        vpMain.setAdapter(pageAdapter);
        vpMain.addOnPageChangeListener(new VpMainChangeListener());
        tlMain.setupWithViewPager(vpMain);
        MyUtil.reflex(tlMain);

        initShare();
    }

    @Override
    protected ProductDetailsPresenter createPresenter() {
        return new ProductDetailsPresenter();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iBtnBack:
                finish();
                break;
            case R.id.llCart:
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra(IntentCode.EXTRA_KEY_FRAGMENT_POSITION, 2);
                startActivity(intent);
                break;
            case R.id.llCollect:
                collect();
                break;
            case R.id.tvAddToCart:
                addCart();
                break;
            case R.id.tvBuyNow:
                buyNow();
                break;
        }
    }

    @Override
    public void onSuccessAddCart() {
        Toast.makeText(this, "加入成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailAddCart(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorAddCart(String error) {
        ToastUtil.showLongToast(this, R.string.network_msg);
    }

    @Override
    public void onSuccessBuyNow(OrderConfirmBean confirmBean) {
        if (confirmBean != null) {
            Intent intent = new Intent(this, ClearingActivity.class);
            intent.putExtra(IntentCode.EXTRA_KEY_CONFIRM_ORDER_DATA, confirmBean);
            startActivity(intent);
        } else {
            Toast.makeText(this, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailBuyNow(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorBuyNow(String error) {
        ToastUtil.showLongToast(this, R.string.network_msg);
    }

    @Override
    public void onSuccessCollect() {
        wash_state = 1;
        ivCollect.setImageDrawable(getResources().getDrawable(R.drawable.icon_collected));
        tvCollect.setText("已收藏");
    }

    @Override
    public void onFailCollect(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorCollect(String msg) {
        ToastUtil.showLongToast(this, R.string.network_msg);
    }

    @Override
    public void onSuccessCancelCollect() {
        wash_state = 0;
        ivCollect.setImageDrawable(getResources().getDrawable(R.drawable.icon_un_collect));
        tvCollect.setText("收藏");
    }

    @Override
    public void onFailCancelCollect(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorCancelCollect(String error) {
        ToastUtil.showLongToast(this, R.string.network_msg);
    }

    class VpMainChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:

                    break;
                case 1:
                    productDetailFragment.update(productId);
                    break;
                case 2:
                    commentFragment.update(productId);
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    /**
     * 初始化分享
     */
    private void initShare() {
        mTencent = Tencent.createInstance(GlobalConfig.QQ_APP_ID, this.getApplicationContext());
        showShareDialog = new ShowShareDialog(this, mTencent);
    }

    /**
     * 添加到购物车
     */
    private void addCart() {
        if (productDetailAll == null) {
            Toast.makeText(this, "数据加载中，请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (release == 1) {
            String token = MyApplication.getToken();
            if (token != null && token.length() > 0) {
                String json = getJsonAddCart();
                if (json != null) {
                    if (productSkuId != 0 && showDialog == false) {
                        presenter.addCart(json, token);
                    } else {
                        introduceFragment.showChooseDialog();
                        showDialog = false;
                    }
                } else {
                    Toast.makeText(this, "请求参数的格式错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                Intent intent = new Intent(this, LoginMainActivity.class);
                startActivity(intent);
            }
        } else if (release == 0) {
            ToastUtil.showLongToast(this, "该商品已下架");
        }

    }

    /**
     * 立即购买
     */
    private void buyNow() {
        if (productDetailAll == null) {
            Toast.makeText(this, "数据加载中，请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (release == 1) {
            String token = MyApplication.getToken();
            if (token != null && token.length() > 0) {
                String json = getJsonBuyNow();
                if (json != null) {
                    if (productSkuId != 0 && showDialog == false) {
                        presenter.buyNow(json, token);
                    } else {
                        introduceFragment.showChooseDialog();
                        showDialog = false;
                    }
                } else {
                    Toast.makeText(this, "请求参数的格式错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                Intent intent = new Intent(this, LoginMainActivity.class);
                startActivity(intent);
            }
        } else if (release == 0) {
            ToastUtil.showLongToast(this, "该商品已下架");
        }

    }

    /**
     * 获取添加到购物车所需要的json参数
     *
     * @return
     */
    private String getJsonAddCart() {
        String json = null;
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject subObject = new JSONObject();
        try {
            subObject.put("buy_num", String.valueOf(num));//购买数量
            //subObject.put("cart_item_id","");//非必传
            subObject.put("product_id", productDetailAll.getId());//商品ID
            subObject.put("product_sku_id", productSkuId);//商品规格id
            subObject.put("supplier_id", productDetailAll.getSupplier_id());//供应商id
            subObject.put("is_install", install);//山门安装
            jsonArray.put(0, subObject);
            object.put("cart_item", jsonArray);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 立即购买 所需要的json参数
     *
     * @return
     */
    private String getJsonBuyNow() {
        String json = null;
        JSONObject object = new JSONObject();
        JSONObject subObj = new JSONObject();
        try {
            subObj.put("buy_num", String.valueOf(num));//购买数量
            subObj.put("product_id", productDetailAll.getId());//商品ID
            //subObj.put("cart_item_id", "");//非必传
            subObj.put("product_sku_id", productSkuId);//商品规格id
            subObj.put("supplier_id", productDetailAll.getSupplier_id());//供应商id
            subObj.put("is_install", install);//上门安装
            object.put("product", subObj);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 收藏
     */
    private void collect() {
        if (wash_state == 0) {
            String token = MyApplication.getToken();
            if (token != null && token.length() > 0) {
                String json = getCollectionJson();
                if (json != null) {
                    presenter.collect(json);
                } else {
                    Toast.makeText(this, "请求参数的格式错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                Intent intent = new Intent(this, LoginMainActivity.class);
                startActivity(intent);
            }
        } else if (wash_state == 1) {
            presenter.cancelCollect(productDetailAll.getId());
        }

    }

    /**
     * 添加收藏json
     * @return
     */
    private String getCollectionJson() {

        JSONObject obj = new JSONObject();
        JSONObject objSub = new JSONObject();
        try {
            objSub.put("product_id", productId);
            objSub.put("customer_id", MyApplication.getUserId());
            obj.put("WishList", objSub);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj.toString();
    }

    /**
     * 更新数据
     */
    public void update(ProductDetailAll productDetailAll) {
        this.productDetailAll = productDetailAll;
        this.wash_state = productDetailAll.getWish_state();
        this.release = productDetailAll.getIs_released();
        this.install = productDetailAll.getIs_install();

        // 收藏
        if (wash_state == 1) {
            ivCollect.setImageDrawable(getResources().getDrawable(R.drawable.icon_collected));
            tvCollect.setText("已收藏");
        }

        showShareDialog.setProductDetailAll(this.productDetailAll);

        //获取微信分享的图片
        Glide.with(this).load(productDetailAll.getIconUrl()).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) resource;
                weChatBip = bitmapDrawable.getBitmap();
                showShareDialog.setBitmap(weChatBip);
            }
        });
    }

    public void setProductSkuId(int productSkuId) {
        this.productSkuId = productSkuId;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public void setShowDialog(boolean showDialog) {
        this.showDialog = showDialog;
    }

    public String getProductId() {
        return productId;
    }

}
